import { HttpException, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { JwtService } from '@nestjs/jwt';
import { EntityManager } from 'typeorm';
import { User } from './entities/user.entity';

@Injectable()
export class UserService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly entityManager: EntityManager,
  ) {}

  async login(createUserDto: CreateUserDto) {
    const user = await this.entityManager.findOne(User, {
      where: {
        username: createUserDto.username,
        password: createUserDto.password,
      },
    });
    if (!user) throw new HttpException('用户名或密码错误', 400);

    const token = this.jwtService.sign({
      username: createUserDto.username,
      id: user.id,
    });

    return { token: 'Bearer ' + token };
  }
}
